package org.chispa.api.visitors;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.chispa.api.util.ExpressionLanguage;

public abstract class SingleParamVisitor<T, R> implements ParamVisitor<T, R,String> {
	
	protected Cipher blockCipher;
	protected SecretKeySpec spec;
	protected IvParameterSpec ivSpec;
	
	SingleParamVisitor(Cipher blockCipher,SecretKeySpec spec,IvParameterSpec ivSpec)
	{
		this.blockCipher=blockCipher;
		this.spec=spec;
		this.ivSpec=ivSpec;
	}
	
	protected String doEncrypt(byte[]parameter) throws InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
	{
		blockCipher.init(Cipher.ENCRYPT_MODE, spec, ivSpec);
		byte[] enc=blockCipher.doFinal(parameter);
		String hexa=new String(Hex.encodeHex(enc));
		return ExpressionLanguage.quote(hexa);
	}
	
	protected String doDecrypt(String hexaEnc)
	{
		try{
			blockCipher.init(Cipher.DECRYPT_MODE, spec, ivSpec);
			byte[]nonHex=Hex.decodeHex(hexaEnc.toCharArray());
			byte[]dec=blockCipher.doFinal(nonHex);
			return new String(dec);
		} catch (Exception e) {
			System.err.println(e.getLocalizedMessage());
			return null;
		}
		
		
	}

}
